package com.plian.system.controller.pm.realproperty;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pm.realproperty.RealProperty;
import com.plian.system.enumeratea.LandStatus;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.model.token.PassToken;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.pm.realproperty.IRealPropertyService;
import com.plian.system.vo.pm.realproperty.RealPropertyFormVO;
import com.plian.system.vo.pm.realproperty.RealPropertyVO;
import com.plian.system.vo.pm.realproperty.RealPropertyYearInfoVO;
import com.plian.system.wrapper.pm.realproperty.RealPropertyWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 不动产登记信息表 控制器
 *
 * @author BladeX
 * @since 2021-05-07
 */
@RestController
@AllArgsConstructor
@RequestMapping("api/realproperty")
@Api(value = "不动产登记信息表", tags = "不动产登记信息表接口")
public class RealPropertyController extends BaseController {

    private final IRealPropertyService realPropertyService;

    private RealPropertyWrapper realPropertyWrapper;

    /**
     * 详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "详情", notes = "传入realProperty")
    public R<RealPropertyVO> detail(@RequestBody RealProperty realProperty) {
        RealProperty detail = realPropertyService.getOne(Condition.getQueryWrapper(realProperty));
        return R.data(realPropertyWrapper.entityToVO(detail));
    }

    @GetMapping("/{initialId}/latest")
    @ApiOperation(value = "根据initialId获取最新的详情", notes = "传入realProperty")
    public R<RealPropertyVO> latest(@PathVariable Long initialId) {
        RealProperty detail = realPropertyService.getOne(Wrappers.<RealProperty>lambdaQuery()
                .eq(RealProperty::getInitialId, initialId)
                .eq(RealProperty::getIsLatest, 2));
        return R.data(realPropertyWrapper.entityToVO(detail));
    }

    /**
     * 分页 不动产登记信息表
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页", notes = "传入query")
    public ListResult<RealPropertyVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<RealProperty> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new RealProperty()), entityList
        );
        TokenSearch<RealProperty> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);
        queryWrapper.eq("form_type", String.valueOf(FormTypeConstant.PM_REAl_PROPERTY));

        IPage<RealProperty> pages = realPropertyService.page(Condition.getPage(query), queryWrapper);
        ListResult<RealPropertyVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(realPropertyWrapper.entityToVO(pages.getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

        return listResult;
    }

    /**
     * 分页 不动产登记信息表
     */
    @PostMapping("/listB")
    @ApiOperation(value = "分页", notes = "传入query")
    public ListResult<RealPropertyVO> listB(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        boolean isKeywords = false;
        String keyWords = new String();
        Integer realPropertyNature = 0;
        if (query != null && query.getSearch() != null) {//解析传参
            List<SearchEntity> searchEntityList = query.getSearch();
            if (searchEntityList != null && searchEntityList.size() > 0) {
//				int num=0;
                for (int i = searchEntityList.size() - 1; i >= 0; i--) {
                    SearchEntity entity = searchEntityList.get(i);
                    String filed = entity.getField();
                    if (StringUtil.isNotBlank(filed)) {
                        if (entity == null || entity.getValue() == null) {
                            searchEntityList.remove(i);
                        } else {
                            if (filed.equals("keywords")) {
                                isKeywords = true;
                                keyWords = (String) entity.getValue();
                                searchEntityList.remove(i);

                            } else {
                                if (filed.equals("real_property_nature")) {
                                    realPropertyNature = (Integer) entity.getValue();
                                }
                                if (filed.equals("apply_company_ids")) {
                                    entity.setField("org_id");
                                }
                            }
                        }


                    }
//					num+=1;
                }
            }
            query.setSearch(searchEntityList);
        }
        QueryWrapper<RealProperty> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new RealProperty()), entityList
        );
        TokenSearch<RealProperty> tokenSearch = new TokenSearch<>();
//		tokenSearch.addTokenQuery(queryWrapper, query);
        queryWrapper.eq("form_type", String.valueOf(FormTypeConstant.PM_REAl_PROPERTY));
        if (realPropertyNature == 1) {
            if (isKeywords) {
                if (StringUtil.isNotBlank(keyWords)) {
                    String finalKeyWords = keyWords;
                    queryWrapper.and(wrapper -> wrapper.like("land_Name", finalKeyWords).or().like("land_located_position", finalKeyWords));
                }
            }
        } else if (realPropertyNature == 2) {
            if (isKeywords) {
                if (StringUtil.isNotBlank(keyWords)) {
                    String finalKeyWords = keyWords;
                    queryWrapper.and(wrapper -> wrapper.like("house_name", finalKeyWords).or().like("house_located_position", finalKeyWords));
                }
            }
        }

        IPage<RealProperty> pages = realPropertyService.page(Condition.getPage(query), queryWrapper);
        ListResult<RealPropertyVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(realPropertyWrapper.entityToVO(pages.getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

        return listResult;
    }

    /**
     * 分页 不动产现状登记信息列表
     */
    @PostMapping("/quoList/{year}")
    @ApiOperation(value = "不动产现状登记信息列表", notes = "传入query")
    public ListResult<RealPropertyYearInfoVO> quoList(@RequestBody Query query, @PathVariable String year) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<RealProperty> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new RealProperty()), entityList
        );
        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());
        queryWrapper.eq("is_latest", "2");
        queryWrapper.le("land_status", LandStatus.CHANGE_AUDIT.getStatus());

        queryWrapper.and(wrapper -> wrapper.eq("is_have_rent_area", 2).or().eq("is_have_fair_value", 2));

        IPage<RealProperty> pages = realPropertyService.page(Condition.getPage(query), queryWrapper);
        ListResult<RealPropertyYearInfoVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(realPropertyService.toQuoList(pages.getRecords(), year));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

        return listResult;
    }

    /**
     * 分页 不动产可变更信息列表
     */
    @PostMapping("/adjustableList")
    @ApiOperation(value = "不动产可变更信息列表", notes = "传入query")
    public ListResult<RealPropertyVO> latestList(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<RealProperty> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new RealProperty()), entityList
        );
        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());
        queryWrapper.eq("is_latest", "2");
        queryWrapper.eq("land_status", LandStatus.ADJUSTABLE.getStatus());

        IPage<RealProperty> pages = realPropertyService.page(Condition.getPage(query), queryWrapper);
        ListResult<RealPropertyVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(realPropertyWrapper.entityToVO(pages.getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());

        return listResult;
    }


    /**
     * 新增或修改 不动产登记信息表
     */
    @PostMapping("/submit")
    @LogOperation("不动产登记信息-提交")
    @Resubmit(delaySeconds = 0)
    @ApiOperation(value = "新增或修改", notes = "传入realProperty")
    public R submit(@Valid @RequestBody RealProperty realProperty) {
        String message = realPropertyService.checkName(realProperty);
        if (StringUtil.isNotBlank(message)) {
            return R.fail(message);
        }
        return R.status(realPropertyService.submit(realProperty));
    }


    /**
     * 删除 不动产登记信息表
     */
    @PostMapping("/remove")
    @LogOperation("不动产登记信息-删除")
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return R.status(realPropertyService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA))));
    }

    /**
     * 模板文件下载
     *
     * @param response
     * @param os
     */
    @GetMapping("/exportTemplateExcel")
    @PassToken
    @ApiOperation(value = "模板文件下载", notes = "模板文件下载")
    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
        realPropertyService.exportTemplateExcel(response, os);
    }

    /**
     * 导入 根据土地名称新增或者覆盖
     */
    @PostMapping("/excelCoverImport")
    @ApiOperation(value = "覆盖导入", notes = "覆盖导入")
    public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String progressId = TokenUtil.getTokenUserId() + "_" + System.currentTimeMillis();
        CacheUtil.put("progress", "progress", progressId + "#half:hour", 0);
        InputStream inputStream = multipartFile.getInputStream();
        realPropertyService.importExcel(progressId, inputStream);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 导入进度查看
     */
    @GetMapping("/progress/{progressId}")
    @ApiOperation(value = "导入进度查看", notes = "导入进度查看")
    public ObjResult progress(@PathVariable String progressId) {
        Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
        if (data != null && data instanceof String) {
            if ("导入成功".equals(data)) {
                ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
                PageData pd = new PageData();
                pd.put("data", 200);
                objResult.setPageData(pd);
                return objResult;
            }
            return new ObjResult(CustomCode.builder().message((String) data).code(1000).success(false).build());
        }
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("data", data);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 委托
     */
    @GetMapping("/entrust")
    @ApiOperation(value = "委托", notes = "委托")
    public R entrust(@RequestBody RealProperty realProperty) {
        String message = realPropertyService.checkEntrust(realProperty);
        if (StringUtil.isNotBlank(message)) {
            return R.fail(message);
        }
        return R.status(realPropertyService.entrust(realProperty));
    }

    /**
     * 取消委托
     */
    @GetMapping("/cancelEntrust")
    @ApiOperation(value = "取消委托", notes = "取消委托")
    public R cancelEntrust(@RequestBody RealProperty realProperty) {
        String message = realPropertyService.checkCancelEntrust(realProperty);
        if (StringUtil.isNotBlank(message)) {
            return R.fail(message);
        }
        return R.status(realPropertyService.cancelEntrust(realProperty));
    }

    /**
     * 不动产登记报表列表 带分页
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @PostMapping("/realPropertyFormList")
    @ApiOperation(value = "不动产登记报表列表", notes = "传入query")
    public ListResult<RealPropertyFormVO> realPropertyFormList(@RequestBody PageData pd) throws Exception {
        Integer pageSize = pd.getInteger("pageSize");
        Integer current = pd.getInteger("current");
        Page<RealPropertyFormVO> page = new Page<>();
        page.setCurrent(current);
        page.setSize(pageSize);
        IPage<RealPropertyFormVO> pages = realPropertyService.formPage(page, pd);
        ListResult<RealPropertyFormVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(pages.getRecords());
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 不动产登记汇总报表列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @PostMapping("/realPropertyGroupFormList")
    @ApiOperation(value = "不动产登记汇总报表列表", notes = "传入query")
    public ListResult<RealPropertyFormVO> realPropertyGroupFormList(@RequestBody PageData pd) throws Exception {
        List<RealPropertyFormVO> list = realPropertyService.formList(pd);
        ListResult<RealPropertyFormVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(list);
        listResult.setTotal(list.size());
        return listResult;
    }

    /**
     * 不动产登记商业体总体情况报表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @PostMapping("/realPropertyHouseBusinessFormList")
    @ApiOperation(value = "不动产登记商业体总体情况报表", notes = "传入query")
    public ListResult<RealPropertyFormVO> realPropertyHouseBusinessFormList(@RequestBody PageData pd) throws Exception {
        List<RealPropertyFormVO> list = realPropertyService.houseBusinessFormList(pd);
        ListResult<RealPropertyFormVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(list);
        listResult.setTotal(list.size());
        return listResult;
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "不动产登记报表导出", notes = "传入query")
    public void exportExcel(@RequestBody PageData pd, HttpServletResponse response) throws Exception {
        Integer pageSize = pd.getInteger("pageSize");
        Integer current = pd.getInteger("current");
        Page<RealPropertyFormVO> page = new Page<>();
        page.setCurrent(current);
        page.setSize(pageSize);
        realPropertyService.exportRepropertyExcel(page, pd, response);
    }

}
